﻿using System;
using System.Runtime.InteropServices;
using System.Security;
namespace LeRenard
{
    /// <summary>
    /// Provides extension methods to interact with <see cref="SecureString"/> objects.
    /// </summary>
    public static class SecureStringExtensions
    {
        /// <summary>
        /// Converst a <see cref="SecureString"/> to a <see cref="String"/>.
        /// </summary>                
        public static string ToUnsecureString(this SecureString secureString)
        {
            ThrowIf.Null(() => secureString);            

            var unmanagedString = IntPtr.Zero;
            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString);
                return Marshal.PtrToStringUni(unmanagedString);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }            
        }
    }
}
